package com.thyrsus.project.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.thyrsus.project.form.event.EventForm;
import com.thyrsus.project.form.search.SearchForm;
import com.thyrsus.project.form.user.UserForm;
import com.thyrsus.project.helper.Constants;
import com.thyrsus.project.helper.SessionHelper;
import com.thyrsus.project.helper.URLHelper;
import com.thyrsus.project.helper.UserHelper;
import com.thyrsus.project.service.event.EventService;

@Controller
@SessionAttributes
public class Home {
	
	@Autowired
	EventService eventService;
	
	@RequestMapping(value = "/home")
	public ModelAndView doHome(HttpServletRequest request,HttpServletResponse response) {
		return doHome(Long.valueOf(1).intValue(),request,response);
    }
	
	@RequestMapping(value = "/home/{tabIndex}")
	public ModelAndView doHome(@PathVariable String tabIndex, Model model, HttpServletRequest request,HttpServletResponse response) {
		return doHome(Long.valueOf(tabIndex).intValue(),request,response);
    }
	
	/**
	 * This function manage the home screen
	 * @param tabIndex the tab to be displayed
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 */
	private ModelAndView doHome(int tabIndex,HttpServletRequest request,HttpServletResponse response) {
		if (!UserHelper.isConnected(request)) {
    		return new ModelAndView(URLHelper.getURL(UserHelper.getLoginURL(request,response, "/home/"+tabIndex),request), "userForm", new UserForm());
    	} else {
    		SessionHelper.setAttribute(request, Constants.TAB_INDEX,tabIndex);
    		ModelAndView mav = new ModelAndView(URLHelper.getURL("/home/home", request));
    		
    		switch (tabIndex) {
			case 1:
				EventForm eventForm = new EventForm();
	    		eventForm.setCreatedEvents(eventService.getCreatedEvent(UserHelper.getUser(request)));
	    		mav.addObject("eventForm", eventForm);
				break;
			case 2:
				SearchForm searchForm = new SearchForm();
				//Add friends
				mav.addObject("searchForm", searchForm);
				break;
			default:
				
				break;
			}
    		
    		return mav;
    	}
	}
}
